package cn.com.coding.framework.security;

import cn.com.coding.system.domin.SysUserEntity;
import cn.com.coding.system.domin.UserInfoEntity;
import cn.com.coding.system.service.SysUserService;
import cn.com.coding.system.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 解决用户登陆查库问题
 *
 * @author mxz
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    UserInfoService userInfoService;

    /**
     * 实现此方法
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserInfoEntity userInfoEntity = userInfoService.getByUserName(username);
        SysUserEntity sysUser = sysUserService.getByUserName(username);
        if (sysUser == null) {
            if (userInfoEntity == null) {
                throw new UsernameNotFoundException("用户名或密码不正确");
            }

            userInfoEntity.setLastLogin(new Date());
            userInfoService.updateById(userInfoEntity);

            // 返回权限
            return new AccountUser(userInfoEntity.getPid(), userInfoEntity.getUserName(), userInfoEntity.getPassword(), getUserAuthority(userInfoEntity.getPid()));
        }
        sysUser.setLastLogin(new Date());
        sysUserService.updateById(sysUser);

        return new AccountUser(sysUser.getPid(), sysUser.getUsername(), sysUser.getPassword(), getUserAuthority(sysUser.getPid()));
    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     *
     * @param userPid
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(String userPid) {

        // 角色(ROLE_admin)  菜单操作权限 sys:user:list
        // ROLE_admin,ROLE_normal,sys:user:list,....
        String authority = sysUserService.getUserAuthorityInfo(userPid);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
